<template>
	<view class="page">
		<view class="my-nav-bar">
			<uni-nav-bar search-icon="search" @onClickSearch="toSearch" color="#222222" background-color="#ffffff" :status-bar="true"
			 left-icon="arrowleft" :left-text="currentChatPerson.realName" :serviceFinished='serviceFinished' :orderMsg="orderMsg"
			 @clickLeft="goBack" fixed="true" />
		</view>
		<!-- 布局 -->
		<scroll-view class="chat-box" :style="{'margin-bottom':inputBottom}">
			<view v-for="(item, key) in currentFeeMsgList(currentChatPerson.userId)" :key="key">
				<view v-if="(item.userInfoId === userInfo.userId && item.type === '0') || 
							(item.expertInfoId === userInfo.userId && item.type === '1')"
				 class="right">
					<view>
						<view style="font-size:12px;color:#999;text-align:right;">{{ item.realName }}</view>
						<view v-if="isPicture(item.note)" class="langcon-r-pic" v-html="chatImage(item.note)"></view>
						<view v-else class="langcon-r" v-html="chatImage(item.note)"></view>
					</view>
					<view style="margin-left:10px;">
						<image :src="userInfo.accountHead" style="width:40px;height:40px;border-radius:50%;border:1px solid #aaa;"
						 mode="aspectFill" />
					</view>
				</view>
				<view class="chat-time" v-else-if="item.type=='time'">
					{{item.time}}
				</view>
				<view v-else class="left">
					<view>
						<image :src="currentChatPerson.accountHead" style="width:40px;height:40px;border-radius:50%;border:1px solid #aaa;" />
					</view>
					<view style="margin-left:10px;">
						<view style="font-size:12px;color:#999;">{{ currentChatPerson.realName }}</view>
						<view v-if="isPicture(item.note)" class="langcon-l-pic" v-html="chatImage(item.note)"></view>
						<view v-else class="langcon-l" v-html="chatImage(item.note)"></view>
					</view>
				</view>
			</view>
		</scroll-view>
		<!-- 输入框 -->

		<view v-if="serviceFinished" class="bottom-done">
			<view class="xinyi" @click="goxinyi" v-if="type =='0'">
				送心意
			</view>
			<view class="btn-continue" @click="goOnPay" v-if="type =='0'">
				继续咨询
			</view>
			<span class="closed" v-if="type =='1'">咨询已结束</span>
		</view>
		<view v-else class="bottom" :style="{'bottom':inputBottom}">
			<view class="bottom-p">
				<view class="bottom-p-l">
					<input type="text" confirm-type="send" @confirm="clickRequest()" placeholder="发送消息" :adjust-position="false"
					 cursor-spacing="50" v-model="value" @focus="textareaFocus" @blur="textareaBlur" /></view>
				<view class="bottom-p-r">
					<view class="bottom-p-picture" @click="camera">
						<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/paizhao_1.png"></image>
					</view>
					<view class="bottom-p-camera" @click="takePicture">
						<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/tupian_1.png"></image>
					</view>
				</view>
			</view>
			<!-- 底部分类 -->
			<!-- <view class="classification">
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/yuyin.png"></image>
				</view>
				<view @click="takePicture">
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/tupian.png"></image>
				</view>
				<view @click="camera">
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/xiangji.png" style="width:25px;height:25px;"></image>
				</view>
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/hongbao.png"></image>
				</view>
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/biaoqing.png" style="width:27px;height:27px;"></image>
				</view>
				<view>
					<image src="https://www.innovationgloble.com/wxs/img/wx/gkxcx/icon/gengduo.png" style="width:27px;height:27px;"></image>
				</view>
			</view> -->
		</view>
		<view class="bottom-fix">
		</view>
	</view>
</template>

<script>
	import uniNavBar from '@/components/uni-nav-bar/uni-nav-bar.vue'
	import {
		mapActions,
		mapState,
		mapMutations,
		mapGetters
	} from 'vuex';
	export default {
		components: {
			uniNavBar,
		},
		data() {
			return {
				value: '',
				tableData: [],
				start: true,
				pageNum: 1,
				linkUserId: '',
				serviceFinished: false, //服务已结束
				type: 0,
				inputBottom: '0',
				picTxtItem: {},
				expertdata: {},
				orderMsg: ''
			};
		},
		computed: {
			...mapState('chatStore', ['currentChatPerson', 'chatListInfo', 'chatFeeLastPage']),
			...mapState('userStore', ['userInfo']),
			...mapGetters('chatStore', ['currentFeeMsgList']),
		},
		methods: {
			...mapActions('chatStore', ['get_chat_fee_list', 'get_user_by_id', 'setUserInfo', 'setCurrentPerson']),
			...mapMutations('chatStore', ['appendFeeChatData', 'appendFeeChatAnswerData']),
			toSearch() {
				console.log(this.userInfo.userId, this.currentChatPerson.userId, this.currentChatPerson.accountHead, this.currentChatPerson
					.realName, this.userInfo.accountHead)
				uni.navigateTo({
					url: `/pagesA/chat-content-search/chat-content-search?type=${this.type}&fromId=${this.userInfo.userId}&toId=${this.currentChatPerson.userId}&accountHead=${this.currentChatPerson.accountHead}&realName=${this.currentChatPerson.realName}&accountHeadSelf=${this.userInfo.accountHead}`
				})
			},
			//获取专家详情
			loadExpertDetails() {
				this.$request.get({
					url: 'ExpertInfo/selectMyExperInfo',
					data: {}
				}).then(res => {
					this.linkUserId = res.linkUserId;
					this.expertdata = res
					this.getExpertFeeInfo(this.linkUserId)
				})
			},
			loadExpertDetailsById() {
				this.$request.get({
					url: 'ExpertInfo/selectExperById',
					data: {
						expertId: this.expertId
					}
				}).then(res => {
					this.linkUserId = res.linkUserId;
					this.expertdata = res
					this.getExpertFeeInfo(this.linkUserId)
				})
			},
			// 图文咨询  电话咨询费
			getExpertFeeInfo(linkUserId) {
				this.$request.get({
					url: 'mallInfo/selectExpert',
					data: {
						"id": linkUserId
					},
				}).then(priceItems => {
					console.log('showByExpertId##', priceItems);
					if (priceItems && priceItems.length !== 0) {
						//获取到 图文咨询
						const picTxtItems = priceItems.filter(item => parseInt(item.typeId) === 2);
						if (picTxtItems.length !== 0) {
							if (parseFloat(picTxtItems[0].isEnable) === 1) {
								this.picTxtItem = picTxtItems[0];
							}
						}
						const phoneItems = priceItems.filter(item => parseInt(item.typeId) === 3);
						if (phoneItems.length !== 0) {
							if (parseFloat(phoneItems[0].isEnable) === 1) {
								this.phoneItem = phoneItems[0];
							}
						}
					}
				}, res => {});
			},
			sendFeeMsg(payload) {
				this.$request.post({
					url: 'expertMsg/send',
					data: payload
				}).then(res => {}, res => {
					if (res.errcode == -1) {
						this.orderMsg = res.errmsg;
					}
					this.serviceFinished = true;
				});
			},
			goxinyi() {
				const accountHead = this.currentChatPerson.accountHead;
				const expertId = this.currentChatPerson.userId;
				const realName = this.currentChatPerson.realName;

				uni.navigateTo({
					url: `/pagesA/send-heart/send-heart?headPortrait=${accountHead}&id=${expertId}&&name=${realName}&linkUserId=${this.userId}`
				});
			},
			goOnPay() {
				// 继续付费
				// const expertId = this.currentChatPerson.userId;
				const linkUserId = this.userId;
				const expertId = this.expertId;
				console.log('专家id',expertId);
				uni.navigateTo({
					url: `/pagesA/text-result/text-result?price=${this.picTxtItem.price}&scene=${this.expertdata.expertId}&linkUserId=${this.expertdata.linkUserId}&name=${this.expertdata.userInfo.realName}&headPortrait=${this.expertdata.headPortrait}`
				});
			},
			//当前 登录用户是否是专家
			isExpert() {
				return false;
			},
			isPicture(content) {
				if (!content) return false;
				if (content.type === 'image') {
					// image
					return true;
				}
				return false;
			},
			chatImage(content) {
				if (!content) return content;
				//字符串类型
				if (typeof(content) === 'string') {
					if (content.indexOf('<img') !== -1) {
						const imgObj = JSON.parse(content);
						return imgObj.value;
					}
					return content;
				}
				// 对象类型
				if (content.type === 'image') {
					return content.value;
				}
				return content;
			},
			clickRequest() {
				if (this.value == '') {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '不能发送空白消息'
					});
				} else {
					let msg = {};
					if (this.type == '0') {
						msg = {
							userInfoId: this.userInfo.userId,
							expertInfoId: this.currentChatPerson.userId,
							note: this.value,
							type: this.type
						}
					} else {
						msg = {
							userInfoId: this.userId,
							expertInfoId: this.expertId,
							note: this.value,
							type: this.type
						}
					}

					const params = {
						fromId: this.userInfo.userId,
						toId: this.currentChatPerson.userId,
						content: this.value,
						sendTime: new Date(),
						type: this.type
					}
					if (this.type == '0')
						this.appendFeeChatData(params);
					else
						this.appendFeeChatAnswerData(params);
					this.sendFeeMsg(msg);
					this.value = '';
					this.scrollToBottom();
				}
			},
			chatList(v) {
				if (this.currentChatPerson) {
					this.setAllRead();
					let params = {};
					if (this.type == '0') {
						params = {
							userInfoId: this.userInfo.userId,
							expertInfoId: this.currentChatPerson.userId,
							pageNum: this.pageNum,
							pageSize: 20,
						}
					} else {
						params = {
							userInfoId: this.userId,
							expertInfoId: this.expertId,
							pageNum: this.pageNum,
							pageSize: 20,
						}
					}
					//非下拉刷新页面拉到底部
					if (!v) {
						params.cb = () => {
							this.scrollToBottom(true);
						}
					}

					this.get_chat_fee_list(params);
				}
			},
			scrollToBottom(v) {
				if (v) {
					this.$nextTick(() => {
						let time = setTimeout(() => {
							let info = uni.createSelectorQuery().select(".chat-box");
							info.boundingClientRect(function(data) { //data - 各种参数
								uni.pageScrollTo({
									// selector: '.bottom-fix',
									scrollTop: data.height, //确保可以自动滚动到底部
									duration: 400,
									success: () => {
										clearInterval(time)
									}
								});
							}).exec()
						}, 1000)

					});
				} else {
					this.$nextTick(() => {
						let info = uni.createSelectorQuery().select(".chat-box");
						info.boundingClientRect(function(data) { //data - 各种参数
							uni.pageScrollTo({
								// selector: '.bottom-fix',
								scrollTop: data.height, //确保可以自动滚动到底部
								duration: 400,

							});
						}).exec()

					});
				}
			},
			createImgContent(fileUrl) {
				const content = "<img src=" + this.$baseUrl + fileUrl + " style='width:240px;object-fit:contain;'>";
				return content;
			},
			uploadPicture(tempFilePaths) {
				const userInfo = uni.getStorageSync('userInfo');
				uni.uploadFile({
					url: this.$baseUrl + 'imFileUploading',
					filePath: tempFilePaths[0],
					formData: {
						model: 'experts'
					},
					name: 'file',
					header: {
						token: userInfo.token
					},
					success: (e) => {
						let res = JSON.parse(e.data);
						if (res.ret) {
							const data = JSON.parse(res.data);
							const fileUrl = data.fileUrl;
							const temp = {
								type: 'image', // text   文本   image 图片   source资源
								// source_type: 'project', // 资源类型
								// id: 0 ,// 相关的资源ID
								value: this.createImgContent(fileUrl)
							}

							let msg = {};
							if (this.type == '0') {
								msg = {
									userInfoId: this.userInfo.userId,
									expertInfoId: this.currentChatPerson.userId,
									note: JSON.stringify(temp),
									type: this.type
								}
							} else {
								msg = {
									userInfoId: this.userId,
									expertInfoId: this.expertId,
									note: JSON.stringify(temp),
									type: this.type
								}
							}
							const params = {
								fromId: this.userInfo.userId,
								toId: this.currentChatPerson.userId,
								content: JSON.stringify(temp),
								sendTime: new Date(),
								type: this.type
							}
							if (this.type == '0')
								this.appendFeeChatData(params);
							else
								this.appendFeeChatAnswerData(params);

							this.sendFeeMsg(msg);
							this.scrollToBottom();
						} else {
							uni.showToast({
								title: res.errmsg,
								icon: 'none'
							})
						}
					},
					fail: res => {
						uni.showToast({
							title: '图片上传失败',
							icon: 'none'
						})
					}
				})
			},
			camera() {
				let _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['camera'], //从相册选择
					success: function(res) {
						_self.uploadPicture(res.tempFilePaths)
					}
				});
			},
			takePicture() {
				let _self = this;
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album'], //从相册选择
					success: function(res) {
						_self.uploadPicture(res.tempFilePaths)
					}
				});
			},
			setAllRead() {
				this.$request.post({
					url: 'im/set_allmsgreaded',
					data: {
						toId: this.userInfo.userId - 0,
						fromId: this.currentChatPerson.userId - 0
					}
				}).then(res => {});

				this.$request.post({
					url: 'im/set_allmsgreaded',
					data: {
						fromId: this.userInfo.userId - 0,
						toId: this.currentChatPerson.userId - 0
					}
				}).then(res => {});
			},
			goBack() {
				uni.navigateBack();
			},
			textareaFocus(e) {
				console.log(e)
				//点击输入框时，获取键盘高度，设置距离底部的高度为键盘的高度  
				this.inputBottom = e.detail.height + 'px';
			},
			textareaBlur(e) {
				//失去焦点时，设置距离底部为0  
				this.inputBottom = ' 0px';
			},
			getCloseMsg(expertId, userId) {
				let that = this;
				this.$request.get({
					url: 'expertOrder/getLastOrder',
					data: {
						expertInfoId: expertId,
						userInfoId: userId
					},
				}).then(res => {
					if (res != null)
						that.orderMsg = res.remarks;
				})
			}
		},
		onShow() {
			getApp().connectWS();
		},
		onUnload() {
			uni.$off('refreshChat'); //在此生命周期里销毁地址改变事件的监听
		},
		onLoad(option) {
			this.serviceFinished = option.finished === 'true';
			this.expertId = option.expertId;
			this.userId = option.userId;

			//0=咨询 1=被咨询
			this.type = option.type;
			if (this.type == '1') {
				this.loadExpertDetails();
			} else {
				this.loadExpertDetailsById();
			}


			const userInfo = uni.getStorageSync('userInfo');
			if (this.type == '0')
				this.getCloseMsg(this.userId, userInfo.userId);
			else
				this.getCloseMsg(userInfo.userId, this.userId);

			this.get_user_by_id({
				userId: this.userId || 85,
				cb: () => {
					if (this.currentChatPerson.realName) {
						this.chatList();
					}
				}
			});
			// 监听到消息 滚动到底部
			uni.$on('refreshChat', () => {
				this.scrollToBottom();
			})
		},
		onPullDownRefresh() {
			if (!this.chatFeeLastPage) {
				this.pageNum += 1;
				this.chatList(true);
			}

			setTimeout(function() {
				uni.stopPullDownRefresh();
			}, 1000);
		}
	};
</script>

<style scoped lang="less">
	.page {
		background-color: #F5F5F5;
		width: 100%;
		min-height: 100vh;
	}

	.bottom-p-r {
		flex: 1;
		display: flex;
		justify-content: space-between;
		padding: 0 25upx;

		.bottom-p-picture {
			vertical-align: middle;
			align-items: center;
			box-sizing: border-box;
			padding-top: 8upx;

			image {
				width: 50upx;
				height: 44upx;
				vertical-align: middle;
			}
		}

		.bottom-p-camera {
			vertical-align: middle;
			align-items: center;
			box-sizing: border-box;
			padding-top: 8upx;

			image {
				width: 50upx;
				height: 44upx;
				vertical-align: middle;
			}
		}
	}

	.my-nav-bar {

		/* position:fixed; */
		/* left:0; */
		/* top:0; */
		/* z-index:99; */
		padding-bottom: 44px;
	}

	.go-back {
		width: 100%;
		height: 128rpx;
		padding-top: 30rpx;
		/* height: var(--status-bar-height);  */
		display: flex;
		align-items: center;
		background: #ffffff;
		padding-left: 30upx;
		/* margin-top: 10upx; */
		position: fixed;
		left: 0;
		top: 0;
		z-index: 99;
	}

	.go-back .back {
		width: 17upx;
		height: 31upx;

	}

	.go-back .name {
		color: #222222;
		font-size: 34upx;
		font-weight: 500;
		margin: 0 18upx 0 22upx;
	}

	.go-back .identity {
		background: rgba(255, 237, 187, .85);
		font-size: 20upx;
		color: #B6890E;
		border-radius: 8upx;
		line-height: 34upx;
		height: 34upx;
		display: inline-block;
		padding: 2upx 14upx;
	}

	.chat-box {
		// margin-bottom: 150upx;
		padding-bottom: 150upx;
		box-sizing: border-box;
		margin-top: 44px;
	}

	.bottom {
		position: fixed;
		bottom: 0;
		width: 100%;
		background: #fff;
		padding-top: 20upx;
		padding-bottom: 20upx;
	}

	.bottom-fix {}


	.bottom-p {
		height: 74upx;
		display: flex;
		justify-content: space-between;
		flex-wrap: nowrap;
	}

	.bottom-p>view:nth-child(1) {
		width: 555upx;
		margin-left: 20upx;
		background-color: #F5F5F5;
		border-radius: 80upx;
		padding: 14upx 0 0 30upx;
		border: solid 1rpx #EDEDED;

	}


	.bottom-done {
		position: fixed;
		bottom: 0;
		height: 140upx;
		width: 100%;
		padding: 20upx 40upx;
		box-sizing: border-box;
		display: flex;
		flex-direction: row;
		align-items: center;
		justify-content: space-between;
		background-color: #FFFFFF;

		.xinyi {
			border-radius: 6upx;
			border: 2upx solid rgba(224, 32, 32, 1);

			width: 320upx;
			height: 80upx;
			background-color: #FFFFFF;
			color: #DE5A02;
			line-height: 80upx;
			text-align: center;
		}

		.closed {
			width: 100%;
			height: 80upx;
			background-color: #dedede;
			color: #bababa;
			line-height: 80upx;
			text-align: center;
		}

		.btn-continue {
			width: 320upx;
			height: 80upx;
			background-color: #008BFF;
			color: #FFFFFF;
			line-height: 80upx;
			text-align: center;
		}
	}


	.center {
		text-align: center;
		font-size: 24upx;
		color: #aaa;
		margin-top: 20upx;
		letter-spacing: 2upx;
	}

	.center {
		text-align: center;
		font-size: 24upx;
		color: #aaa;
		margin-top: 20upx;
		letter-spacing: 2upx;
	}

	.left {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-start;
		margin-left: 20upx;
		margin-top: 20upx;
	}

	.right {
		display: flex;
		flex-wrap: nowrap;
		justify-content: flex-end;
		margin-right: 20upx;
		margin-top: 20upx;
	}

	.langcon-l-pic {
		font-size: 28upx;
		color: #414141;
		line-height: 60upx;
		border-radius: 14upx;
		margin-top: 10upx;
		margin-left: 20upx;
	}

	.langcon-l {
		font-size: 28upx;
		color: #414141;
		line-height: 60upx;
		border-radius: 14upx;
		margin-top: 10upx;
		/* text-align: right; */
		padding: 6upx 20upx 6upx 20upx;
		background: #fff;
		margin-left: 20upx;
	}

	.langcon-r-pic {
		font-size: 28upx;
		color: #fff;
		line-height: 60upx;
		border-radius: 14upx;
		margin-top: 10upx;
		/* text-align: right; */
		padding: 6upx 20upx 6upx 20upx;
		/* background: ; */
		margin-left: 30upx;
	}

	.langcon-r {
		font-size: 28rpx;
		color: #fff;
		line-height: 60rpx;
		border-radius: 14rpx 0 14rpx 14rpx;
		margin-top: 10rpx;
		padding: 6rpx 20rpx 6rpx 20rpx;
		background: #008BFF;
		margin-left: 30rpx;
		word-break: break-word;
		max-width: 510rpx;
	}

	.langcon-r-pic rich-text>img {
		width: 200upx !important;
		object-fit: contain;
		border-radius: 10upx;
	}

	.langcon-l-pic rich-text>img {
		width: 200upx !important;
		object-fit: contain;
		border-radius: 10upx;
	}

	/* 	.zs {
		font-size: 12px;
		letter-spacing: 1px;
		color: #AAAAAA;
		margin-top: 5px;
		text-align: center;
	} */

	/* 分类 */
	.classification {
		display: flex;
		flex-wrap: nowrap;
		justify-content: space-between;
		width: 90%;
		margin: 0 auto;
		padding-top: 20upx;
	}

	.classification image {
		width: 42upx;
		height: 42upx;
	}

	.chat-time {
		text-align: center;
		font-size: 24upx;
		color: #999;

	}
</style>
